import $ from './library/jquery.js';
import cookie from './library/cookie.js';
import querystring from './library/querystring.js';

// 通过search 获得商品id
let id = location.search.split('=')[1];

$.ajax({
    type: "get",
    url: "../../interface/getItem.php",
    data: { id: id },
    dataType: "json",

}).then(function (res) {
    // console.log(res);
    // console.log(res.title);
    let temp = `<p>${res.title}</p>`;
    $('.main-title').html(temp);

    let price = `<span>¥</span>
    <b>${res.price}</b>`;
    $('.main-r-3').html(price);

    let color = res.color;
    // console.log(color);
    $('.phone-color').html(color);

    let storage = res.storage;
    // console.log(storage);
    $('.phone-rom').html(storage);


    $('#numSub').on('click', function () {
        console.log(1);
    });
    $('#numAdd').on('click', function () {
        console.log(1);
    });

    $('#addItem').on('click', function () {
        addItem(res.id, res.price, $('#num-shop').val());

    });

}).catch(function (xhr) {
    console.log(xhr.status)
});

function addItem(id, price, num) {

    let shop = cookie.get('shop'); // 获取购物车信息
    let product = {
        id: id,
        price: price,
        num: num
    }
    console.log(product);
    // 判断当前cookie中是否存有购物车数据
    if (shop) {  // 如果有数据 数据将是字符串格式
        shop = JSON.parse(shop);  // 转对象(数组)
        // 判断传入的id是否重复
        if (shop.some(elm => elm.id === id)) {
            let _index = shop.findIndex(el => el.id === id);
            let count = parseInt(shop[_index].num);
            count += parseInt(num);
            shop[_index].num = count;
        } else {
            shop.push(product);
        }
    } else { // 初始化情况下没有数据
        shop = [];  // 初始化一个数组
        shop.push(product); // 将商品加入购物车数据
    }

    cookie.set('shop', JSON.stringify(shop), 1);
}

$('.common-tog').on('click', function () {
    $(this).children().slice(3).toggleClass('color-tog');
})
